/**
 * 
 */
package com.ipeony.tools;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 * @author iPeony
 * @version v0.1
 * @category Tool
 */
public class IntegerPartitions extends JFrame {

	/**
	 * 序列化
	 */
	private static final long serialVersionUID = 4714227753555822279L;
	public static double CYLINDER_SIZE = 7.84423828125; // 柱面大小

	private static void createAndShowGUI() {
		// Create and set up the window.
		JFrame frame = new JFrame("整数分区计算");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// Set up the content pane.
		addComponentsToPane(frame.getContentPane());
		//Set window To center
		frame.setLocationRelativeTo(null);
		// Display the window.
		frame.pack();
		frame.setVisible(true);
	}

	public static void addComponentsToPane(Container pane) {

		jLabel = new JLabel("请输入整数分区(G):");
		jTextField = new JTextField(10);
		jButton = new JButton("给我算！");
		jTextField.setDocument(new PlainDocument() {

			/**
			 * 序列化
			 */
			private static final long serialVersionUID = -7371552707247241300L;

			@Override
			public void insertString(int offs, String str, AttributeSet a)
					throws BadLocationException {
				try {
					Integer.parseInt(str);
				} catch (Exception e) {
					return;
				}
				if (jTextField.getText().length() > 10)
					return;
				super.insertString(offs, str, a);
			}

		});
		jButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				String partitionStr = jTextField.getText();
				int partitonNum = Integer.valueOf(partitionStr);
				String result = calcIntegerPartitions(partitonNum);
				JOptionPane.showInputDialog(jButton, "结果,单位为M,直接ctr+c吧", "结果",
						JOptionPane.INFORMATION_MESSAGE, null, null, result);
			}
		});
		pane.setLayout(new FlowLayout());
		pane.add(jLabel);
		pane.add(jTextField);
		pane.add(jButton);
	}

	/**
	 * @param null
	 */

	public static void main(String[] args) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});
	}

	/**
	 * @param num
	 *            需要的整数分区
	 * @return 分区以兆(M)为单位的数值
	 */
	private static String calcIntegerPartitions(int num) {
		int cylinderNum = (int) Math.ceil(num * 1024 / CYLINDER_SIZE);
		return (int) Math.ceil(cylinderNum * CYLINDER_SIZE) + "";
	}

	private static JLabel jLabel;
	private static JTextField jTextField;
	private static JButton jButton;
}
